<template>
  <div class="container">
    <h1 class="text-2xl font-bold mb-4">违章事故分析</h1>
    
    <div class="mb-4 flex items-center space-x-4">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="dateShortcuts"
        value-format="YYYY-MM-DD"
        @change="handleDateChange"
      />
      <el-select v-model="selectedVehicle" placeholder="选择车辆" clearable @change="loadData">
        <el-option
          v-for="vehicle in vehicles"
          :key="vehicle.id"
          :label="vehicle.vehicleNo"
          :value="vehicle.id"
        />
      </el-select>
      <el-select v-model="reportType" placeholder="报表类型" @change="loadData">
        <el-option label="违章分析" value="violation" />
        <el-option label="事故分析" value="accident" />
        <el-option label="综合分析" value="all" />
      </el-select>
      <el-button type="primary" @click="loadData">查询</el-button>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">违章总数</h2>
        <p class="text-3xl font-bold text-orange-500">{{ stats.totalViolations }}</p>
      </el-card>
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">违章罚款总额</h2>
        <p class="text-3xl font-bold text-red-500">{{ formatCurrency(stats.totalViolationFine) }}</p>
      </el-card>
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">事故总数</h2>
        <p class="text-3xl font-bold text-blue-500">{{ stats.totalAccidents }}</p>
      </el-card>
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">事故损失总额</h2>
        <p class="text-3xl font-bold text-purple-500">{{ formatCurrency(stats.totalAccidentCost) }}</p>
      </el-card>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
      <el-card shadow="hover" class="h-80">
        <template #header>
          <div class="flex justify-between items-center">
            <span>违章类型分布</span>
          </div>
        </template>
        <div ref="violationTypeChart" class="h-full w-full"></div>
      </el-card>
      
      <el-card shadow="hover" class="h-80">
        <template #header>
          <div class="flex justify-between items-center">
            <span>事故类型分布</span>
          </div>
        </template>
        <div ref="accidentTypeChart" class="h-full w-full"></div>
      </el-card>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
      <el-card shadow="hover" class="h-80">
        <template #header>
          <div class="flex justify-between items-center">
            <span>违章趋势</span>
            <el-radio-group v-model="trendTimeUnit" size="small" @change="updateTrendCharts">
              <el-radio-button label="month">月度</el-radio-button>
              <el-radio-button label="quarter">季度</el-radio-button>
              <el-radio-button label="year">年度</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="violationTrendChart" class="h-full w-full"></div>
      </el-card>
      
      <el-card shadow="hover" class="h-80">
        <template #header>
          <div class="flex justify-between items-center">
            <span>事故趋势</span>
          </div>
        </template>
        <div ref="accidentTrendChart" class="h-full w-full"></div>
      </el-card>
    </div>
    
    <el-card shadow="hover" class="mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <span>驾驶员违章/事故排名</span>
          <el-radio-group v-model="driverRankType" size="small" @change="updateDriverRankChart">
            <el-radio-button label="violation">违章次数</el-radio-button>
            <el-radio-button label="accident">事故次数</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div ref="driverRankChart" style="height: 400px; width: 100%"></div>
    </el-card>
    
    <el-card shadow="hover" class="mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <span>违章/事故明细</span>
          <el-button type="primary" size="small" @click="exportReport">导出报表</el-button>
        </div>
      </template>
      
      <el-tabs v-model="detailTab" @tab-click="handleTabClick">
        <el-tab-pane label="违章记录" name="violation">
          <el-table :data="violationRecords" border stripe style="width: 100%">
            <el-table-column prop="date" label="违章日期" width="120" />
            <el-table-column prop="vehicleNo" label="车牌号" width="120" />
            <el-table-column prop="driver" label="驾驶员" width="100" />
            <el-table-column prop="violationType" label="违章类型" width="120" />
            <el-table-column prop="location" label="违章地点" min-width="180" />
            <el-table-column prop="fine" label="罚款金额(元)" width="120">
              <template #default="scope">
                {{ scope.row.fine.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="points" label="扣分" width="80" />
            <el-table-column prop="status" label="处理状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === '已处理' ? 'success' : 'warning'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="事故记录" name="accident">
          <el-table :data="accidentRecords" border stripe style="width: 100%">
            <el-table-column prop="date" label="事故日期" width="120" />
            <el-table-column prop="vehicleNo" label="车牌号" width="120" />
            <el-table-column prop="driver" label="驾驶员" width="100" />
            <el-table-column prop="accidentType" label="事故类型" width="120" />
            <el-table-column prop="location" label="事故地点" min-width="150" />
            <el-table-column prop="description" label="事故描述" min-width="180" />
            <el-table-column prop="damageCost" label="损失金额(元)" width="120">
              <template #default="scope">
                {{ scope.row.damageCost.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="responsibility" label="责任认定" width="120" />
            <el-table-column prop="status" label="处理状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === '已处理' ? 'success' : 'danger'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      
      <div class="mt-4 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRecords"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  name: 'TrafficAccidentView',
  setup() {
    // 图表实例
    let violationTypeChartInstance = null
    let accidentTypeChartInstance = null
    let violationTrendChartInstance = null
    let accidentTrendChartInstance = null
    let driverRankChartInstance = null
    
    // 图表DOM引用
    const violationTypeChart = ref(null)
    const accidentTypeChart = ref(null)
    const violationTrendChart = ref(null)
    const accidentTrendChart = ref(null)
    const driverRankChart = ref(null)
    
    // 数据状态
    const vehicles = ref([])
    const selectedVehicle = ref('')
    const dateRange = ref([])
    const reportType = ref('all')
    const trendTimeUnit = ref('month')
    const driverRankType = ref('violation')
    const detailTab = ref('violation')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalRecords = ref(0)
    const violationRecords = ref([])
    const accidentRecords = ref([])
    
    // 统计数据
    const stats = reactive({
      totalViolations: 0,
      totalViolationFine: 0,
      totalAccidents: 0,
      totalAccidentCost: 0
    })
    
    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '最近三个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          return [start, end]
        },
      },
      {
        text: '最近半年',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
          return [start, end]
        },
      },
      {
        text: '今年',
        value: () => {
          const end = new Date()
          const start = new Date(new Date().getFullYear(), 0, 1)
          return [start, end]
        },
      },
    ]
    
    // 模拟数据
    const mockData = {
      // 违章类型分布
      violationTypes: [
        { value: 35, name: '超速行驶' },
        { value: 25, name: '违规停车' },
        { value: 15, name: '闯红灯' },
        { value: 10, name: '不系安全带' },
        { value: 15, name: '其他' }
      ],
      // 事故类型分布
      accidentTypes: [
        { value: 40, name: '追尾碰撞' },
        { value: 30, name: '刮蹭' },
        { value: 15, name: '倒车碰撞' },
        { value: 10, name: '侧面碰撞' },
        { value: 5, name: '其他' }
      ],
      // 违章趋势
      violationTrend: {
        months: ['1月', '2月', '3月', '4月', '5月', '6月'],
        data: [8, 12, 15, 10, 20, 18]
      },
      // 事故趋势
      accidentTrend: {
        months: ['1月', '2月', '3月', '4月', '5月', '6月'],
        data: [2, 1, 3, 2, 4, 3]
      },
      // 驾驶员排名
      driverRank: {
        drivers: ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'],
        violationCounts: [12, 8, 7, 6, 5, 4, 3, 2],
        accidentCounts: [3, 1, 0, 2, 1, 0, 1, 0]
      },
      // 违章记录
      violationRecords: [
        {
          date: '2023-06-15',
          vehicleNo: '京A12345',
          driver: '张三',
          violationType: '超速行驶',
          location: '北京市海淀区中关村大街',
          fine: 200,
          points: 3,
          status: '已处理'
        },
        {
          date: '2023-06-10',
          vehicleNo: '京B67890',
          driver: '李四',
          violationType: '违规停车',
          location: '北京市朝阳区建国路',
          fine: 150,
          points: 2,
          status: '未处理'
        },
        {
          date: '2023-06-05',
          vehicleNo: '京C54321',
          driver: '王五',
          violationType: '闯红灯',
          location: '北京市西城区西长安街',
          fine: 300,
          points: 6,
          status: '已处理'
        }
      ],
      // 事故记录
      accidentRecords: [
        {
          date: '2023-06-20',
          vehicleNo: '京A12345',
          driver: '张三',
          accidentType: '追尾碰撞',
          location: '北京市海淀区中关村大街',
          description: '在等红灯时被后车追尾',
          damageCost: 5000,
          responsibility: '对方全责',
          status: '已处理'
        },
        {
          date: '2023-06-08',
          vehicleNo: '京D98765',
          driver: '赵六',
          accidentType: '刮蹭',
          location: '北京市东城区东长安街',
          description: '停车时与旁边车辆发生轻微刮蹭',
          damageCost: 2000,
          responsibility: '双方各50%责任',
          status: '未处理'
        }
      ]
    }
    
    // 初始化
    onMounted(() => {
      // 初始化日期范围为近三个月
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      dateRange.value = [formatDate(start), formatDate(end)]
      
      // 加载数据
      loadVehicles()
      loadData()
      
      // 初始化图表
      nextTick(() => {
        initCharts()
      })
    })
    
    // 加载车辆列表
    const loadVehicles = async () => {
      try {
        // 实际项目中应从API获取
        /*
        const response = await axios.get('/api/vehicles')
        vehicles.value = response
        */
        
        // 模拟数据
        vehicles.value = [
          { id: 1, vehicleNo: '京A12345' },
          { id: 2, vehicleNo: '京B67890' },
          { id: 3, vehicleNo: '京C54321' },
          { id: 4, vehicleNo: '京D98765' },
          { id: 5, vehicleNo: '京E13579' }
        ]
      } catch (error) {
        ElMessage.error('获取车辆列表失败')
        console.error('获取车辆列表失败:', error)
      }
    }
    
    // 加载数据
    const loadData = async () => {
      try {
        // 实际项目中应从API获取数据
        /*
        const params = {
          startDate: dateRange.value[0],
          endDate: dateRange.value[1],
          vehicleId: selectedVehicle.value,
          reportType: reportType.value,
          page: currentPage.value,
          size: pageSize.value
        }
        const response = await axios.get('/api/reports/traffic-accident', { params })
        // 使用API返回的数据更新统计和图表
        */
        
        // 使用模拟数据更新
        if (detailTab.value === 'violation') {
          violationRecords.value = mockData.violationRecords
          totalRecords.value = mockData.violationRecords.length
        } else {
          accidentRecords.value = mockData.accidentRecords
          totalRecords.value = mockData.accidentRecords.length
        }
        
        // 更新统计数据
        stats.totalViolations = 83
        stats.totalViolationFine = 18500
        stats.totalAccidents = 15
        stats.totalAccidentCost = 45000
        
        // 更新图表
        updateCharts()
      } catch (error) {
        ElMessage.error('加载数据失败')
        console.error('加载数据失败:', error)
      }
    }
    
    // 更新所有图表
    const updateCharts = () => {
      nextTick(() => {
        initViolationTypeChart()
        initAccidentTypeChart()
        updateTrendCharts()
        updateDriverRankChart()
      })
    }
    
    // 更新趋势图表
    const updateTrendCharts = () => {
      initViolationTrendChart()
      initAccidentTrendChart()
    }
    
    // 初始化违章类型分布图表
    const initViolationTypeChart = () => {
      if (violationTypeChartInstance) {
        violationTypeChartInstance.dispose()
      }
      
      violationTypeChartInstance = echarts.init(violationTypeChart.value)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}次 ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 0,
          data: mockData.violationTypes.map(item => item.name)
        },
        series: [
          {
            name: '违章类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: mockData.violationTypes
          }
        ]
      }
      
      violationTypeChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        violationTypeChartInstance.resize()
      })
    }
    
    // 初始化事故类型分布图表
    const initAccidentTypeChart = () => {
      if (accidentTypeChartInstance) {
        accidentTypeChartInstance.dispose()
      }
      
      accidentTypeChartInstance = echarts.init(accidentTypeChart.value)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}次 ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 0,
          data: mockData.accidentTypes.map(item => item.name)
        },
        series: [
          {
            name: '事故类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: mockData.accidentTypes
          }
        ]
      }
      
      accidentTypeChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        accidentTypeChartInstance.resize()
      })
    }
    
    // 初始化违章趋势图表
    const initViolationTrendChart = () => {
      if (violationTrendChartInstance) {
        violationTrendChartInstance.dispose()
      }
      
      violationTrendChartInstance = echarts.init(violationTrendChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}次'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: mockData.violationTrend.months
        },
        yAxis: {
          type: 'value',
          name: '违章次数'
        },
        series: [
          {
            name: '违章次数',
            type: 'line',
            data: mockData.violationTrend.data,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: '#FF9F43'
            },
            itemStyle: {
              color: '#FF9F43'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(255, 159, 67, 0.5)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(255, 159, 67, 0.1)'
                  }
                ]
              }
            }
          }
        ]
      }
      
      violationTrendChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        violationTrendChartInstance.resize()
      })
    }
    
    // 初始化事故趋势图表
    const initAccidentTrendChart = () => {
      if (accidentTrendChartInstance) {
        accidentTrendChartInstance.dispose()
      }
      
      accidentTrendChartInstance = echarts.init(accidentTrendChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}次'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: mockData.accidentTrend.months
        },
        yAxis: {
          type: 'value',
          name: '事故次数'
        },
        series: [
          {
            name: '事故次数',
            type: 'bar',
            data: mockData.accidentTrend.data,
            barWidth: '50%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#6193FE' },
                { offset: 1, color: '#92B7FF' }
              ])
            }
          }
        ]
      }
      
      accidentTrendChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        accidentTrendChartInstance.resize()
      })
    }
    
    // 更新驾驶员排名图表
    const updateDriverRankChart = () => {
      if (driverRankChartInstance) {
        driverRankChartInstance.dispose()
      }
      
      driverRankChartInstance = echarts.init(driverRankChart.value)
      
      const data = driverRankType.value === 'violation' ? 
        mockData.driverRank.violationCounts : mockData.driverRank.accidentCounts
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const value = params[0].value
            const name = params[0].name
            const type = driverRankType.value === 'violation' ? '违章' : '事故'
            return `${name}: ${value}次${type}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: driverRankType.value === 'violation' ? '违章次数' : '事故次数'
        },
        yAxis: {
          type: 'category',
          data: mockData.driverRank.drivers,
          axisTick: {
            alignWithLabel: true
          }
        },
        series: [
          {
            name: driverRankType.value === 'violation' ? '违章次数' : '事故次数',
            type: 'bar',
            data: data,
            label: {
              show: true,
              position: 'right',
              formatter: '{c}次'
            },
            itemStyle: {
              color: driverRankType.value === 'violation' ? 
                '#FF9F43' : '#6193FE'
            }
          }
        ]
      }
      
      driverRankChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        driverRankChartInstance.resize()
      })
    }
    
    // 处理日期变化
    const handleDateChange = () => {
      loadData()
    }
    
    // 处理标签页切换
    const handleTabClick = (tab) => {
      loadData()
    }
    
    // 处理页面大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadData()
    }
    
    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadData()
    }
    
    // 导出报表
    const exportReport = () => {
      ElMessage.success('报表导出成功')
      // 实际项目中应调用导出API
      // window.location.href = '/api/reports/traffic-accident/export?startDate=' + dateRange.value[0] + '&endDate=' + dateRange.value[1]
    }
    
    // 格式化货币
    const formatCurrency = (value) => {
      return value.toLocaleString('zh-CN', { 
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }) + '元'
    }
    
    // 日期格式化
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    return {
      vehicles,
      selectedVehicle,
      dateRange,
      dateShortcuts,
      reportType,
      trendTimeUnit,
      driverRankType,
      stats,
      detailTab,
      violationRecords,
      accidentRecords,
      currentPage,
      pageSize,
      totalRecords,
      violationTypeChart,
      accidentTypeChart,
      violationTrendChart,
      accidentTrendChart,
      driverRankChart,
      loadData,
      handleDateChange,
      handleTabClick,
      handleSizeChange,
      handleCurrentChange,
      updateTrendCharts,
      updateDriverRankChart,
      formatCurrency,
      exportReport
    }
  }
}
</script> 